<?php
namespace Home\Controller;
use Common\Controller\CommonController;

/**
 * 集采礼品
 * @author 张亚伟 <zhangyw@zhijin101.com>
 */
class JcGiftController extends CommonController
{
    
    public function index(){
        $map = [];
        list($list, $page) = $this->lists('JcGift', $map, 'id asc');
        $this->assign('page', $page);
        $this->assign('list', $list);
        $this->display();
    }

    public function add() {
        if (IS_POST) {
            $data = I('post.');
            if (empty($data['gift_name'])) {
                $this->ajaxReturn(array('s' => false, 'm' => '请输入商品名称'));
            }
            if (empty($data['img'])) {
                $this->ajaxReturn(array('s' => false, 'm' => '请上传图片'));
            }
            $data['create_time'] = time();
            $data['update_time'] = time();
            $model = M('JcGift');
            $id = $model->add($data);
            if ($id) {
                $this->ajaxReturn(array('s' => true, 'm' => '添加成功', 'url' => U('index')));
            } else {
                $this->ajaxReturn(array('s' => false, 'm' => '添加失败!'));
            }
        } else {
            $this->display();
        }
    }

    public function edit(){
        $id = I('id');
        if (IS_POST) {
            $data = I('post.');
            if (empty($data['gift_name'])) {
                $this->ajaxReturn(array('s' => false, 'm' => '请输入商品名称'));
            }
            if (empty($data['img'])) {
                $this->ajaxReturn(array('s' => false, 'm' => '请上传图片'));
            }

            $model = M('JcGift');

            $data['update_time'] = time();
            $res = $model->where(['id' => $id])->save($data);
            if ($res !== false) {
                $this->ajaxReturn(array('s' => true, 'm' => '修改成功', 'url' => U('index')));
            } else {
                $this->ajaxReturn(array('s' => false, 'm' => '修改失败!'));
            }
        } else {
            $info = M('JcGift')->where(['id' => $id])->find();
            $this->assign('info', $info);
            $this->display();
        }
    }

    public function del(){
        $id = I('id');
        $res = M('JcGift')->where(['id' => $id])->delete();
        if ($res) {
            $this->ajaxReturn(array('s' => true, 'm' => '删除成功', 'url' => U('index')));
        } else {
            $this->ajaxReturn(array('s' => false, 'm' => '删除失败!'));
        }
    }
}